package com.chushouya.product.dao.repository;


import com.general.framework.core.lang.Longs;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import com.chushouya.product.dao.entity.EvaluateLogEntity;
import com.chushouya.product.dao.mapper.EvaluateLogEntityMapper;
import com.chushouya.product.dto.admin.evaluatelog.EvaluateLogQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;


@Repository
@Slf4j
public class EvaluateLogRepository extends BaseRepository<EvaluateLogEntityMapper, EvaluateLogEntity, Long> {


    public List<EvaluateLogEntity> selectList(EvaluateLogQuery query) {
        return selectByExample(buildExample(query));
    }

    public PageResult<EvaluateLogEntity> selectPageResult(EvaluateLogQuery query) {
        return this.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public EvaluateLogEntity selectOne(EvaluateLogQuery query) {
        return selectFirstOneByExample(buildExample(query));
    }

    public EvaluateLogEntity selectByEvaluateNo(String evaluateId) {
        EvaluateLogQuery query = new EvaluateLogQuery();
        query.setEvaluateId(evaluateId);
        return selectOne(query);
    }
    
    /**
     * 根据用户ID获取最新的评估记录
     * 
     * @param userId 用户ID
     * @return 最新的评估记录
     */
    public EvaluateLogEntity selectLatestByUserId(Long userId) {
        EvaluateLogQuery query = new EvaluateLogQuery();
        query.setUserId(userId);
        Example example = buildExample(query);
        example.orderBy("evaluateLogId").desc();
        return this.selectFirstOneByExample(example);
    }




    private Example buildExample(EvaluateLogQuery query) {
        Example example = this.buildExample();
        if (Strings.isNotEmpty(query.getEvaluateId())) {
            example.and().andEqualTo("evaluateId", query.getEvaluateId());
        }
        if (Longs.notNullAndZero(query.getProductId())) {
            example.and().andEqualTo("goodsId", query.getProductId());
        }
        if (Longs.notNullAndZero(query.getUserId())) {
            example.and().andEqualTo("userId", query.getUserId());
        }
        if (Longs.notNullAndZero(query.getCategoryId())) {
            example.and().andEqualTo("categoryId", query.getCategoryId());
        }
        if (Longs.notNullAndZero(query.getBrandId())) {
            example.and().andEqualTo("brandId", query.getBrandId());
        }
        if (Objects.nonNull(query.getStartTime())&&Objects.nonNull(query.getEndTime())) {
            example.and().andBetween("createTime", query.getStartTime(), query.getEndTime());
        }
        example.orderBy("evaluateLogId").desc();
        return example;

    }
}